package main

import (
	"apis"
	"config"
	"controller"
	"log"
	"spirit/mongodb"
	"spirit/web/core"

	"github.com/gin-gonic/gin"
)

func main() {
	router := core.InitFramework(registerRouter)
	initIndicatorData()
	initHistoryYearIdCards()
	router.Run(core.GetConfiguration().App.ServerPort)
}

func initIndicatorData() {
	log.Println("加载当前年度指标数据......")
	query := make(map[string]interface{}, 0)
	query["year"] = config.CurrentYear
	config.CurrentIndicator = *(mongodb.Find("indicator", query, `{"_id":1}`, nil, false, -1, -1))
	log.Printf("当前年度:[%s],指标:%v", config.CurrentYear, config.CurrentIndicator)
}

func initHistoryYearIdCards() {
	log.Println("加载历史年度筛查人员身份信息缓存......")
	queryTbNames := make([]string, 0)
	queryTbNames = append(queryTbNames, config.CurrentYear)
	for _, year := range config.ScreenYearRecord {
		if !excludeYearCheck(year) {
			queryTbNames = append(queryTbNames, year)
		}
	}

	data := make([]map[string]interface{}, 0)
	for _, year := range queryTbNames {
		tb := "infoCollection_" + year
		log.Printf("加载[%s]年缓存数据...", year)
		m := *(mongodb.Find(tb, `{}`, `{"_id":-1}`, `{"baseInfo.idCard":1,"baseInfo.userName":1}`, false, 0, 15000))
		data = append(data, m...)
	}
	for _, val := range data {
		if val["baseInfo"] != nil {
			baseInfo := val["baseInfo"].(map[string]interface{})
			idCard := baseInfo["idCard"].(string)
			userName := baseInfo["userName"].(string)
			config.IdCardCaches.Store(idCard, userName)
		}
	}
	//query["baseInfo.idCard"] = config.CurrentYear
	//config.CurrentIndicator = *(mongodb.Find("indicator", query, `{"_id":1}`, nil, false, -1, -1))
	log.Printf("加载完毕缓存人数:[%d]", len(data))
}

func excludeYearCheck(year string) bool {
	for _, y := range config.ScreenExcludeYear {
		if year == y {
			return true
		}
	}
	return false
}

func registerRouter(r *gin.Engine) {
	new(controller.InfoCollectionController).Router(r)
	new(controller.LoginController).Router(r)
	new(controller.SystemUserController).Router(r)
	new(controller.OrdinaryUserController).Router(r)
	new(apis.ApiController).Router(r)
}
